package com.rocksea.app;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.mor.dataacquisition.DataAcquisition;
import com.mor.dataacquisition.net.DataCallBack;
import com.mor.dataacquisition.net.parsedData.ResponseData;
import com.mor.dataacquisition.vo.highStrain.HighStrain;
import com.mor.dataacquisition.vo.lowStrain.LowStrain;
import com.mor.dataacquisition.vo.lowStrain.LowStrainData;
import com.mor.dataacquisition.vo.staticLoad.StaticLoadLog;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.StaticLoad.StaticLoad;
import com.rocksea.app.db.UpLoadingTable;
import com.rocksea.app.db.UploadingDbHelper;
import com.rocksea.app.db.history.HistoryTable;
import com.rocksea.app.db.image.ImageTable;
import com.rocksea.app.db.lowStrain.LowStrainDb;
import com.rocksea.app.http.HttpUtil;
import com.rocksea.app.http.UpDateRandomCodeTask;
import com.rocksea.app.http.UpLoadSonicWaveThread;
import com.rocksea.app.http.UploadImageThread;
import com.rocksea.app.utils.HttpMessage;
import com.rocksea.app.utils.UiUtils;

import java.io.File;

/**
 * @author by Mrw_v @date on 2018/9/28
 *
 */

public class UploadingTask
{
    private static DataAcquisition mDataAcquisition;
    private static boolean mWorking = true;

    // <editor-fold desc="初始化">
    public static void init()
    {
        mDataAcquisition = DataAcquisition.getInstance();
    }
    // </editor-fold>

    // <editor-fold desc="上传低应变数据">
    public static void uploadStrain(final Context context, final LowStrainDb lowStrainDb)
    {
        if (!mWorking)
            return;
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传%s桩基本信息",lowStrainDb.pileNo));
        LowStrain lowStrain = lowStrainDb.getLowStrain((int) lowStrainDb.inspectionFormId,lowStrainDb.inspectionFormNum,lowStrainDb.pileId);
        mDataAcquisition.uploadLowStrain(lowStrain,context,new DataCallBack<ResponseData>()
        {
            @Override
            public void processData(ResponseData data)
            {
                int code = data.returnCode;
                if (code > 0)
                {
                    DbCenter.insertLowStrainServiceId(lowStrainDb.uuid,code);
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"低应变基本信息上传成功,开始上传采样数据");
                    uploadLowStrainData(context,lowStrainDb,code);
                }
                else if (code == -98)
                {
                    int serviceId = lowStrainDb.serviceId;
                    uploadLowStrainData(context,lowStrainDb,serviceId);
                }
                else if (code == -1)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.WARM,"登录验证失效,正在重新验证");
                    UpDateRandomCodeTask.startTask();
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {uploadStrain(context,lowStrainDb);
                        }
                    });
                }
                else
                {
                    String message = HttpMessage.getErrorInfo(HttpMessage.uploadLowStrain,code);
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,String.format("上传失败%s",message));
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {uploadStrain(context,lowStrainDb);
                        }
                    });
                }
            }
        });
    }

    private static void uploadLowStrainData(Context context, LowStrainDb mLowStrainDb, int serviceId)
    {
        if (!mWorking)
            return;
        if (mLowStrainDb.lowStrainDataDb == null || mLowStrainDb.lowStrainDataDb.size() == 0)
        {
            HttpUtil.postEvent(HttpUtil.UploadEvent.WARM,"未查询到有采样数据");
            return;
        }
        int index = 0;
        for (int i = 0; i < mLowStrainDb.lowStrainDataDb.size(); i++)
        {
            if (DbCenter.mDyDbHelper.isWaveDataUpLoad(mLowStrainDb.lowStrainDataDb.get(index).uuid))
            {
                index++;
                continue;
            }
            break;
        }

        if (index == mLowStrainDb.lowStrainDataDb.size())
        {
            HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"采样数据已全部上传完成");
            UploadingDbHelper.makeUnloading(mLowStrainDb.uuid,HistoryTable.TEST_DY,UpLoadingTable.DEFAULT_UUID);
            return;
        }

        LowStrainData lowStrainData = mLowStrainDb.getBJTKStarinData(serviceId,index);
        final String uuid =  mLowStrainDb.lowStrainDataDb.get(index).uuid;
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传第%s锤数据",lowStrainData.curNumber));
        mDataAcquisition.uploadLowStrainData(lowStrainData,context, new LowStrainDataUploadCallBack(uuid,index,mLowStrainDb, context, serviceId));
    }

    private static class LowStrainDataUploadCallBack extends DataCallBack<ResponseData>
    {
        private String uuid;
        private int index;
        private LowStrainDb lowStrainDb;
        private Context context;
        private int serviceId;

        LowStrainDataUploadCallBack(String uuid, int index, LowStrainDb LowStrainDb, Context context, int serviceId)
        {
            this.uuid = uuid;
            this.index = index;
            this.lowStrainDb = LowStrainDb;
            this.context = context;
            this.serviceId = serviceId;
        }

        @Override
        public void processData(ResponseData data)
        {
            int code = data.returnCode;
            if (code == 0 || code == -98)
            {
                DbCenter.makeAsLowStrainDataUpLoad(uuid);
                index++;
                if (index == lowStrainDb.lowStrainDataDb.size())
                {
                    UploadingDbHelper.makeUnloading(lowStrainDb.uuid,HistoryTable.TEST_DY,UpLoadingTable.DEFAULT_UUID);
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"采样数据上传完成");
                    DbCenter.makeAsUpLoaded(lowStrainDb.uuid, HistoryTable.TEST_DY);
                    overDYTesting(lowStrainDb.uuid,serviceId,lowStrainDb.lowStrainDataDb.size());
                    return;
                }
            }
            else if (code == -1)
            {
                HttpUtil.postEvent(HttpUtil.UploadEvent.WARM,"登录验证失效,正在重新验证");
                UpDateRandomCodeTask.startTask();
            }
            else
            {
                String message = HttpMessage.getErrorInfo(HttpMessage.upLowStrainData,data.returnCode);
                HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,String.format("上传失败(%s)",message));
            }
            postRunnable(new Runnable()
            {
                @Override
                public void run()
                {uploadLowStrainData(context, lowStrainDb, serviceId);
                }
            });
        }
    }
    // </editor-fold>

    // <editor-fold desc="上传高应变数据">
    public static void uploadHighStrainData(final com.rocksea.app.db.HighStrain.HighStrain highStrain, final Context context)
    {
        if (!mWorking)
            return;
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传 %s桩数据",highStrain.pileNo));
        HighStrain uploadHighStrain = highStrain.getBJHighStrain(highStrain.inspectionFormId,highStrain.inspectionFormNum,highStrain.pileId);
        mDataAcquisition.uploadHighStrain(uploadHighStrain,context,new DataCallBack<ResponseData>()
        {
            @Override
            public void processData(ResponseData data)
            {
                int code = data.returnCode;
                if (code >= 0 || code == -98)
                {
                    UploadingDbHelper.makeUnloading(highStrain.uuid,HistoryTable.TEST_GY,UpLoadingTable.DEFAULT_UUID);
                    DbCenter.makeAsUpLoaded(highStrain.uuid,HistoryTable.TEST_GY);
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("%s桩上传成功",highStrain.pileNo));
                }
                else if (code == -1)
                {
                    UpDateRandomCodeTask.startTask();
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            uploadHighStrainData(highStrain, context);
                        }
                    });
                }
                else
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,String.format("%s桩 上传失败(%s)",highStrain.pileNo,HttpMessage.getErrorInfo(HttpMessage.uploadHighStrain,code)));
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            uploadHighStrainData(highStrain, context);
                        }
                    });
                }
            }
        });
    }
    // </editor-fold>

    // <editor-fold desc="上传静载数据">
    public static void uploadStaticLoad(StaticLoad staticLoad,Context context)
    {
        if (!mWorking)
            return;
        int serviceId = staticLoad.serviceId;
        if (serviceId > 0)
        {
            if (HttpUtil.isFileAutoUpload())
            {
                UploadingDbHelper.makeUnloading(staticLoad.baseInfoId,HistoryTable.TEST_JZ, UpLoadingTable.DEFAULT_UUID);
            }
            upLoadStaticSample(staticLoad,context,serviceId);
            return;
        }
        com.mor.dataacquisition.vo.staticLoad.StaticLoad uploadStaticLoad = staticLoad.getBJYKStaticLoad((int) staticLoad.inspectionFormId,staticLoad.inspectionFormNum,staticLoad.pileId);
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传%s桩数据",staticLoad.pileNo));
        mDataAcquisition.uploadStaticLoad(uploadStaticLoad,context,new StaticLoadUploadCallBack(staticLoad, context));
    }

    private static class StaticLoadUploadCallBack extends DataCallBack<ResponseData>
    {
        private StaticLoad staticLoad;
        private Context context;

        private StaticLoadUploadCallBack(StaticLoad staticLoad, Context context)
        {
            this.staticLoad = staticLoad;
            this.context = context;
        }

        @Override
        public void processData(ResponseData data)
        {
            int code = data.returnCode;
            if (code > 0)
            {
                if (HttpUtil.isFileAutoUpload())
                {
                    UploadingDbHelper.makeUnloading(staticLoad.baseInfoId,HistoryTable.TEST_JZ, UpLoadingTable.DEFAULT_UUID);
                }
                DbCenter.insertServiceId(staticLoad.baseInfoId,code);
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("%s桩基本信息上传完成",staticLoad.pileNo));
                upLoadStaticSample(staticLoad,context,code);
            }
            else if (code == -98)
            {
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("%s桩基本信息上传完成",staticLoad.pileNo));
                int serviceId = staticLoad.serviceId;
                upLoadStaticSample(staticLoad,context,serviceId);
            }
            else if (code == -1)
            {
                UpDateRandomCodeTask.startTask();
                postRunnable(new Runnable() {
                    @Override
                    public void run() {uploadStaticLoad(staticLoad,context);
                    }
                });
            }
            else
            {
                String message = String.format("桩号%s(%s)",staticLoad.pileNo,HttpMessage.getErrorInfo(HttpMessage.uploadStaticLoad,code));
                HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,message);
                postRunnable(new Runnable() {
                    @Override
                    public void run() {uploadStaticLoad(staticLoad,context);
                    }
                });
            }
        }
    }

    private static void upLoadStaticSample(StaticLoad staticLoad,Context context,int serviceId)
    {
        if (!mWorking)
            return;
        int sampleIndex = 0;
        if (staticLoad.mStaticLoadTest.size() == 0)
        {
            HttpUtil.postEvent(HttpUtil.UploadEvent.WARM,"未查询到采样数据");
            return;
        }
        for (int i = 0; i < staticLoad.mStaticLoadTest.size(); i++)
        {
            if (DbCenter.mStaticLoadDbHelper.isDataUpLoad(staticLoad.mStaticLoadTest.get(i).uuid))
            {
                sampleIndex++;
            }
        }
        if (sampleIndex == staticLoad.mStaticLoadTest.size())
        {
            uploadStaticLog(staticLoad,context,serviceId);
            return;
        }
        com.mor.dataacquisition.vo.staticLoad.StaticLoadTest uploadStaticLoadTest = staticLoad.getBJTKStaticLoadTest(serviceId,staticLoad.mStaticLoadTest.get(sampleIndex),sampleIndex+1);
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传第%s级第%s次采样数据",uploadStaticLoadTest.grade,uploadStaticLoadTest.sampleCount));
        mDataAcquisition.uploadStaticLoadTest(uploadStaticLoadTest,context,new SampleUploadCallBack(serviceId,context,staticLoad,sampleIndex));
    }

    private static class SampleUploadCallBack extends DataCallBack<ResponseData>
    {
        private int serviceId;
        private Context context;
        private StaticLoad staticLoad;
        private int sampleIndex;

        private SampleUploadCallBack(int serviceId, Context context, StaticLoad staticLoad,int sampleIndex)
        {
            this.serviceId = serviceId;
            this.context = context;
            this.staticLoad = staticLoad;
            this.sampleIndex = sampleIndex;
        }

        @Override
        public void processData(ResponseData data)
        {
            int code = data.returnCode;
            StaticLoad.StaticLoadTest uploadStaticLoadTest = staticLoad.mStaticLoadTest.get(sampleIndex);
            if (code == 0 || code == -98)
            {
                UploadingDbHelper.makeUnloading(staticLoad.baseInfoId,HistoryTable.JY_SAMPLE_DATA,uploadStaticLoadTest.uuid);
                DbCenter.makeUpLoaded(staticLoad.mStaticLoadTest.get(sampleIndex).uuid,DbCenter.JY_SAMPLE_DATE);
                sampleIndex++;
                if (sampleIndex == staticLoad.mStaticLoadTest.size())
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"采样数据上传完成");
                    uploadStaticLog(staticLoad,context,serviceId);
                }
            }
            else if (code == -1)
            {
                UpDateRandomCodeTask.startTask();
            }
            else
            {
                String message = String.format("第%s级第%s次采样数据上传异常(%s)",
                        uploadStaticLoadTest.grade,
                        uploadStaticLoadTest.sampleCount,
                        HttpMessage.getErrorInfo(HttpMessage.uploadStaticLoadTest,code));
                HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,message);
            }
            postRunnable(new Runnable() {
                @Override
                public void run() {upLoadStaticSample(staticLoad,context,serviceId);
                }
            });
        }
    }

    private static int i = 0;
    private static void uploadStaticLog(StaticLoad staticLoad,Context context,int serviceId)
    {
        if (!mWorking)
            return;
        int logIndex = 0;
        if (staticLoad.mStaticLoadLog.size() == 0)
        {
            overJYTesting(staticLoad.baseInfoId,serviceId,staticLoad.mStaticLoadTest.size(),staticLoad.mStaticLoadLog.size());
            return;
        }

        for (int i = 0; i < staticLoad.mStaticLoadLog.size(); i++)
        {
            if (DbCenter.mStaticLoadDbHelper.isLogUpLoad(staticLoad.mStaticLoadLog.get(i).uuid))
            {
                logIndex++;
            }
        }
        if (logIndex == staticLoad.mStaticLoadLog.size())
        {
            overJYTesting(staticLoad.baseInfoId,serviceId,staticLoad.mStaticLoadTest.size(),staticLoad.mStaticLoadLog.size());
            return;
        }

        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传第%s次测试日志",logIndex+1));
        StaticLoadLog uploadStaticLog = staticLoad.getBJTJStaticLoadLog(serviceId,staticLoad.mStaticLoadLog.get(logIndex),logIndex+1);
        mDataAcquisition.uploadStaticLoadLog(uploadStaticLog,context,new StaticLogUploadCallBack(serviceId,context,staticLoad,logIndex));
        i++;
        Log.d("uploadStaticLog: ","count = " + i);

    }

    private static class StaticLogUploadCallBack extends DataCallBack<ResponseData>
    {
        private int serviceId;
        private Context context;
        private StaticLoad staticLoad;
        private int logIndex;

        private StaticLogUploadCallBack(int serviceId, Context context, StaticLoad staticLoad, int logIndex)
        {
            this.serviceId = serviceId;
            this.context = context;
            this.staticLoad = staticLoad;
            this.logIndex = logIndex;
        }

        @Override
        public void processData(ResponseData data)
        {
            int code = data.returnCode;
            StaticLoad.StaticLoadLog staticLoadLog = staticLoad.mStaticLoadLog.get(logIndex);
            if (code == 0 || code == -98)
            {
                DbCenter.makeUpLoaded(staticLoadLog.uuid,DbCenter.JY_LOG_DATE);
                UploadingDbHelper.makeUnloading(staticLoad.baseInfoId,HistoryTable.JY_LOG_DATA,staticLoadLog.uuid);
                logIndex++;
                if (logIndex == staticLoad.mStaticLoadLog.size())
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"测试日志上传完成");
                    uploadImage(staticLoad.pileNo,staticLoad.inspectionFormNum);
                    overJYTesting(staticLoadLog.baseInfoId,serviceId,staticLoad.mStaticLoadTest.size(),staticLoad.mStaticLoadLog.size());
                }
            }
            else if (code == -1)
            {
                UpDateRandomCodeTask.startTask();
            }
            else
            {
                String message = String.format("第%s次日志上传异常(%s)",logIndex+1,HttpMessage.getErrorInfo(HttpMessage.uploadStaticLoadLog,data.returnCode));
                HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,message);

            }
            postRunnable(new Runnable() {
                @Override
                public void run()
                {
                    uploadStaticLog(staticLoad,context,serviceId);
                }
            });

        }
    }
    // </editor-fold>
    private static void postRunnable(Runnable runnable)
    {
        new Handler().postDelayed(runnable,1000);
    }

    // <editor-fold desc="结束试验">
    private static void overJYTesting(final String baseInfoId, final int serviceId, final int validDataCount, final int validLogCount)
    {
        if (!mWorking)
            return;
        // 在测试的状态或者数据没有全部上传都不结束实验
        if (DbCenter.mStaticLoadDbHelper.isTesting(baseInfoId) || !DbCenter.mStaticLoadDbHelper.isSampleAndLogUploaded(baseInfoId))
        {
             HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"空闲");
             return;
        }
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"正在结束实验...");
        mDataAcquisition.pileTestEnd(Account.getRandomCode(),Account.getAccount(),serviceId,4,validDataCount,validLogCount,MyApplication.getContext(),new DataCallBack<ResponseData>()
        {
            @Override
            public void processData(ResponseData data)
            {
                int code = data.returnCode;
                if (code == 0 || code == -6)
                {
                    UploadingDbHelper.makeUnloading(baseInfoId,HistoryTable.TEST_JZ, UpLoadingTable.DEFAULT_UUID);
                    DbCenter.makeAsUpLoaded(baseInfoId, HistoryTable.TEST_JZ);
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"结束实验成功");
                }
                else if (code == -1)
                {
                    UpDateRandomCodeTask.startTask();
                    postRunnable(new Runnable() {
                        @Override
                        public void run() { overJYTesting(baseInfoId, serviceId, validDataCount, validLogCount); }
                    });
                }
                else
                {
                    String message = String.format("实验结束失败(%s)!", HttpMessage.getErrorInfo(HttpMessage.pileTestEnd,data.returnCode));
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,message);
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            overJYTesting(baseInfoId, serviceId, validDataCount,validLogCount);
                        }
                    });
                }
            }
        });
    }

    private static void overDYTesting(final String baseInfoId, final int serviceId, final int validDataCount)
    {
        if (!mWorking)
            return;
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"正在结束实验...");
        mDataAcquisition.pileTestEnd(Account.getRandomCode(),Account.getAccount(),serviceId,1,validDataCount,0,MyApplication.getContext(),new DataCallBack<ResponseData>()
        {
            @Override
            public void processData(ResponseData data)
            {
                int code = data.returnCode;
                if (code == 0)
                {
                    DbCenter.makeAsUpLoaded(baseInfoId, HistoryTable.TEST_DY);
                    HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"结束实验成功");
                }
                else if (code == -1)
                {
                    UpDateRandomCodeTask.startTask();
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            overDYTesting(baseInfoId, serviceId, validDataCount);
                        }
                    });
                }
                else
                {
                    String message = String.format("实验结束失败(%s)!", HttpMessage.getErrorInfo(HttpMessage.pileTestEnd,data.returnCode));
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,message);
                    postRunnable(new Runnable() {
                        @Override
                        public void run() {
                            overDYTesting(baseInfoId, serviceId, validDataCount);
                        }
                    });
                }
            }
        });
    }
    // </editor-fold>

    // <editor-fold desc="上传图片">
    public static void uploadImage(String pileNo,String planNum)
    {
        UploadImageThread uploadImageThread = new UploadImageThread(planNum,pileNo);
        uploadImageThread.start();
    }

    public static void uploadImage(final ImageTable imageTable)
    {
        if (imageTable.getIsSonicWave() == 0)
        {
           mDataAcquisition.uploadImage(
                   Account.getRandomCode(),
                   Account.getAccount(),
                   new File(imageTable.getFilePath()),
                   imageTable.getPileId(),
                   imageTable.getPlanNum(),
                   imageTable.getPileNo(),
                   imageTable.getType(),
                   imageTable.getCreatTime(),
                   imageTable.getRemake(),
                   0,
                   "0",
                   MyApplication.getContext(),
                   new DataCallBack<ResponseData>()
                   {
                        @Override
                        public void processData(ResponseData data)
                        {
                            super.processData(data);
                            if (data.returnCode==0)
                            {
                                UiUtils.showToast("上传成功");
                                DbCenter.makeImageAsUpLoad(imageTable.getPileId(),imageTable.getFileName());
                            }
                            else if (data.returnCode == -1)
                            {
                                UpDateRandomCodeTask.startTask();
                                UiUtils.showToast("验证失效，请稍后再试");
                            }
                            else
                                UiUtils.showToast(String.format("上传失败(%s)",data.returnCode));
                        }
                   });
        }
    }
    // </editor-fold>

    // <editor-fold desc="开始和结束任务">
    public static void cancel()
    {
        UpLoadSonicWaveThread.exitUploadThread();
        UploadImageThread.exitUploadImageThread();
        mWorking = false;
        HttpUtil.postEvent(HttpUtil.UploadEvent.WARM,"已取消上传");
    }

    public static void startTask()
    {
        mWorking = true;
    }
    // </editor-fold>

}
